using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace YouTubeDupe
{
    /// <summary>
    /// A set of static methods used to communicate with the YouTube developer API.
    /// </summary>
    public class YouTubeAPI
    {
        static bool _connectionExists = false;

        /// <summary>
        /// True if a connection to the API exists; false otherwise.
        /// </summary>
        public static bool ConnectionExists
        {
            get
            {
                if (!_connectionExists)
                {
                    WebRequest request = WebRequest.Create(@"http://www.youtube.com/api2_rest");
                    try
                    {
                        HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            _connectionExists = false;
                        }
                        else
                        {
                            System.IO.StreamReader reader = new StreamReader(response.GetResponseStream());
                            if (reader.ReadLine().Contains("fail"))
                            {
                                _connectionExists = false;
                            }
                            else
                            {
                                _connectionExists = true;
                            }
                        }
                    }
                    catch (WebException)
                    {
                        _connectionExists = false;
                    }
                }

                return _connectionExists;
            }
        }

        /// <summary>
        /// Checks a YouTube API developer id.
        /// </summary>
        /// <param name="id">The developer id to check.</param>
        /// <returns>True if a valid id is provided; false otherwise.</returns>
        public static bool CheckDeveloperID(string id)
        {
            string requestUrl = @"http://www.youtube.com/api2_rest?method=youtube.users.get_profile&dev_id=" + id + "&user=user";
            HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string responseText = reader.ReadToEnd();

                if (responseText.Contains("status=\"fail\""))
                {
                    return false;
                }

                return true;
            }
        }

        public static int GetVideoCount(string tag, string developerId)
        {
            string url = @"http://www.youtube.com/api2_rest?method=youtube.videos.list_by_tag&dev_id=" + developerId + "&tag=" + tag + "&page=1&per_page=1";
            WebRequest request = WebRequest.Create(url);
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            System.Xml.XmlReader reader = System.Xml.XmlReader.Create(response.GetResponseStream());

            bool in_video_list = false;
            while (reader.Read())
            {
                if (reader.Name.Equals("video_list") && reader.NodeType == System.Xml.XmlNodeType.Element)
                {
                    in_video_list = true;
                }
                else if (in_video_list && reader.Name.Equals("total") && reader.NodeType == System.Xml.XmlNodeType.Element)
                {
                    return int.Parse(reader.ReadElementContentAsString());
                }
            }

            return 0;
        }

        public static string GetPageOfVideos(string tag, int page, int videosPerPage, string developerId)
        {
            string url = @"http://www.youtube.com/api2_rest?method=youtube.videos.list_by_tag&dev_id=" + developerId + "&tag=" + tag + "&page=" + page + "&per_page=" + videosPerPage;
            string returnedXml = null;
            WebRequest request = WebRequest.Create(url);
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            using (System.IO.StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                returnedXml = reader.ReadToEnd();
                reader.Close();
            }

            return returnedXml;
        }
    }
}
